<template>
  <div class="view-detail" :class="fontSize">
    <div class="header">
      <h2>{{detail.view.title}}</h2>
      <p v-if="!preview" class="time">发布时间：{{detail.view.publishTime | dateFormat('YYYY-MM-DD HH:mm')}}</p>
    </div>
    <div class="main">
      <div class="view-info">
        <van-image lazy-load  width="35px" height="35px" round :src="detail.view.tgInfo.avatar" class="avatar" @click.native="$router.push(`/adviser/detail/${detail.view.tgInfo.id}/`)"/>
        <div class="info">
          <p class="name">{{detail.view.tgInfo.name}}</p>
          <p class="license">执业证号：{{adviser.tgInfo.license}}</p>
        </div>
        <div style="flex: 1; text-align: right;">
          <van-button v-if="adviser.isFollow === 1" size="small" color="linear-gradient(to right, #ED7F31, #E8302E)" @click="follow(-1)">已关注</van-button>
          <van-button v-else size="small" color="linear-gradient(to right, #ED7F31, #E8302E)" @click="follow(1)">关注</van-button>
        </div>
      </div>
      <div class="summary">
        <span>摘要：</span>
        <p>{{detail.view.summary}}</p>
      </div>
      <template v-if="detail.stocks.length">
        <h3 style="margin-bottom: 15px;">关联个股</h3>
        <div class="stock-list">
          <horizontal-scroll-list>
            <horizontal-scroll-item v-for="stock in detail.stocks" :key="stock.code">
              <div class="stock" v-if="detail.view.costType == 2 && !hasAuth && !preview">
                <p>***</p>
                <p>({{stock.code.slice(0, 3)}}***)</p>
              </div>
              <div class="stock" v-else @click="toStockDetail(stock.code, stock.market)">
                <p>{{stock.name}}</p>
                <p>({{stock.code}})</p>
              </div>
            </horizontal-scroll-item>
          </horizontal-scroll-list>
        </div>
      </template>
      <div v-for="p in detail.paragraphs" :key="p.title" style="margin-bottom: 20px;" class="paragraphs">
        <div v-if="preview">
          <h3>{{p.title}}</h3>
          <div class="content" v-html="p.content" @click="onContentClick"></div>
        </div>
        <div class="lock" v-else-if="p.auth === 2 && !isLogin">
          <van-icon name="lock" size="40" color="#f1bfa4"></van-icon>
          <p>剩余阅读{{p.wordNum}}字，手机号登录可见全部</p>
          <van-button round type="danger" @click="login" >立即登录查看</van-button>
        </div>
        <div class="lock" v-else-if="p.auth === 3 && !isFundLogin">
          <van-icon name="lock" size="40" color="#f1bfa4"></van-icon>
          <p>剩余阅读{{p.wordNum}}字，资金账号登录可见全部</p>
          <van-button round type="danger" @click="fundLogin">立即登录查看</van-button>
        </div>
        <div class="lock" v-else-if="p.auth === 4 && !hasAuth">
          <van-icon name="lock" size="40" color="#f1bfa4"></van-icon>
          <p>剩余阅读{{p.wordNum}}字，解锁可见全部</p>
          <van-button plain round type="danger" @click="single=true;buy()" v-if="detail.view.price > 0">
            解锁单篇
            <span style="margin-left: 15px;">{{detail.view.price | numberFormat('0.00')}}元</span>
          </van-button>
          <template v-if="detail.view.inPackage == 1">
            <p>订阅观点包更划算</p>
            <van-button round type="danger" @click="signle=false;buy()">
              <span v-if="price.price === price.oldPrice">订阅观点包 {{price.price}}</span>
              <span v-else>订阅观点包 {{price.price}} <a style="text-decoration: line-through;" v-show="price.oldPrice">{{`原价${price.oldPrice}`}}</a></span>
            </van-button>
          </template>
        </div>
        <div v-else>
          <h3>{{p.title}}</h3>
          <div class="content" v-html="p.content" @click="onContentClick"></div>
        </div>
      </div>
      <van-row type="flex" justify="space-around" class="btn-group" v-if="!preview">
        <van-col>
          <van-button class="like-btn red-btn" v-if="detail.extension.isLike === 1" icon="good-job" round @click="like(-1)">{{detail.view.likeCount}}</van-button>
          <van-button class="like-btn gray-btn" v-else icon="good-job" round @click="like(1)">{{detail.view.likeCount}}</van-button>
        </van-col>
        <van-col>
          <van-button class="gray-btn" icon="share" round @click="share">分享</van-button>
        </van-col>
      </van-row>
      <div class="adv" v-for="card in detail.cards" :key="card.name"  @click="$router.push(CARD_TYPE[card.type].path.replace(':id', card.id))">
        <van-tag type="danger">{{CARD_TYPE[card.type].name}}</van-tag>
        <span class="name">{{card.title}}</span>
        <p>{{card.summary}}</p>
      </div>
    </div>
    <div class="notice van-hairline--top">
      【风险提示】投资顾问提供的观点和投资建议仅供参考，不作为客户投资决策依据，客户需独立作出投资决策，风险自担。市场有风险，投资需谨慎。
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import { Button, Row, Col, Icon, Tag, Popup, Loading, ImagePreview, Dialog } from 'vant';
import { getViewApp, likeView, getPreview } from '../../api/view';
import { getTgDetail, followTg } from '../../api/adviser';
import { shareLink, toStockDetail, closeWebView } from '../../api/native';
import HorizontalScrollList from '../../components/HorizontalScrollList.vue';
import HorizontalScrollItem from '../../components/HorizontalScrollItem.vue';
import isEmpty from 'lodash/isEmpty';

// 类型 1: 直播, 2: 观点, 3: 组合, 4: 锦囊, 5: 视频, 6: 问答, 9: 投顾
const CARD_TYPE = {
  1: {
    name: '直播',
    path: '/live/:id/history/'
  },
  2: {
    name: '观点',
    path: '/view/detail/:id'
  },
  3: {
    name: '组合',
    path: '/portfolio/detail/:id'
  }
}

export default {
  components: {
    [Button.name]: Button,
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Popup.name]: Popup,
    [Loading.name]: Loading,
    HorizontalScrollList,
    HorizontalScrollItem,
  },

  props: {
    preview: {
      type: Boolean,
      default: false
    },

    id: {
      type: String,
    }
  },

  data() {
    return {
      imageDialog: '',
      detail: {
        view: {
          productGroup: {},
          tgInfo: {}
        },
        cards: [],
        paragraphs: [],
        extension: {},
        stocks: [],
      },
      show: false,
      image: {
        width: 0,
        height: 0,
        src: ''
      },
      loading: false,
      adviser: {
        tgInfo: {}
      },
      single: false,
      hasAuth: false,
      CARD_TYPE,
      fontSize: 'normal',
      commissionTable: [],
      product: {
        products: []
      },
    }
  },

  mounted() {
    this.$setTitle('观点详情');
    if(this.preview) {
      return this.getPreview().then(() => this.getTgDetail(this.detail.view.tgInfo.id));
    }
    this.getViewApp().then(() => {
      this.getTgDetail(this.detail.view.tgInfo.id);
    });
  },

  beforeDestroy() {
    if(this.imageDialog !== ''){
      this.imageDialog.close();
    }
  },

  computed: {
    ...mapGetters(['isLogin', 'isFundLogin']),
  },

  methods: {
    ...mapActions(['login', 'fundLogin']),

    ...{
      toStockDetail
    },

    async getViewApp() {
      try {
        const data = await getViewApp(this.id);
        this.detail = data.data;
        if(this.detail.view.status === 4) {
          Dialog.alert({
            message: '此观点已下架'
          }).then(() => closeWebView())
        }
      } catch (error) {
        console.error(error);
      }
    },

    async getPreview() {
      try {
        const data = await getPreview(this.id);
        this.detail = data.data;
      } catch (error) {
        console.error(error);
      }
    },

    async getTgDetail(tgId) {
      try {
        const data = await getTgDetail(tgId);
        this.adviser = data.data;
      } catch (error) {
        console.error(error);
      }
    },

    async like(isLike) {
      if(!this.isLogin) {
        return this.login();
      }
      const data = await likeView(this.id, isLike);
      if(data.code === 0) {
        this.detail.extension.isLike = -this.detail.extension.isLike;
        if(isLike === 1) {
          this.detail.view.likeCount = this.detail.view.likeCount + 1;
          this.$toast('点赞成功');
        } else {
          this.detail.view.likeCount = this.detail.view.likeCount - 1;
          this.$toast('取消点赞成功');
        }
      } else {
        this.$toast(data.message);
      }
    },

    async follow(isFollow) {
      if(!this.isLogin) {
        return this.login();
      }
      const data = await followTg(this.adviser.tgInfo.id, isFollow);
      if(data.code ===0) {
        this.adviser.isFollow = -this.adviser.isFollow;
        if(isFollow === 1) {
          this.$toast('关注成功');
        } else {
          this.$toast('取消关注成功');
        }
      } else {
        this.$toast(data.message);
      }
    },

    share() {
      shareLink({
        url: location.href,
        title: this.detail.view.title,
        message: this.detail.view.summary
      })
    },

    onContentClick(e) {
      if(e.target.tagName === 'IMG') {
        this.imageDialog = ImagePreview([e.target.src.replace("/resize", "")]);
      }
    }
  }
};
</script>

<style lang="less">
.view-detail {
  .main, .header {
    padding: 15px;
    background: #fff;
  }

  .main {
    margin-top: 10px;
  }

  .header {
    h2 {
      font-size: 18px;
      color: #2b313d;
    }

    .time {
      margin-top: 10px;
      color: #919bb2;
      font-size: 14px;
    }
  }

  .view-info {
    display: flex;
    align-items: center;
    font-size: 13px;
    line-height: 1.3;
    color: #5d667a;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e1e6;

    .van-button {
      line-height: 25px;
      height: 25px;
      width: 50px;
      font-size: 12px;
      white-space: nowrap;
    }

    .license {
      font-size: 10px;
    }

    .avatar {
      display: inline-block;
      border-radius: 50%;
      width: 35px;
      height: 35px;
      margin-right: 10px;
    }

    .name {
      color: #121d32;
      font-size: 14px;
    }
  }

  .summary {
    background-color: #f5f6f6;
    color: #5e616b;
    padding: 10px;
    margin: 20px 0;
    font-size: 14px;
    line-height: 1.45;

    p {
      text-align: justify;
    }
  }

  .stock-list {
    border-top: 1px solid #e0e1e6;
    border-bottom: 1px solid #e0e1e6;
    margin-bottom: 20px;

    .stock {
      background: #FFFFFF;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.10);
      border-radius: 4px;
      margin: 15px;
      padding: 15px 30px;
      line-height: 1.5;
    }
  }

  .paragraphs {
    h3 {
      margin-bottom: 10px;
    }

    .content {
      line-height: 24px;
      color: #333;
      font-size: 18px;
      text-align: justify;

      * {
        max-width: 100%;
        word-break: break-all;
      }

      ol {
        list-style: decimal;
      }

      ul {
        list-style: unset;
      }

      li {
        margin-left: 20px;
      }

      img {
        max-width: 100%;
        display: block;
      }
    }
  }

  .lock {
    margin: 15px 0;
    background: #f5f6f6;
    padding: 30px;
    text-align: center;

    p {
      margin: 20px 0;
      color: #5d667a;
      font-size: 14px;
    }

    .van-button {
      width: 100%;

      &.van-button--plain {
        background-color: transparent;
      }
    }
  }

  .adv {
    margin: 15px 0;
    background: #fff;
    padding: 15px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.10);
    border-radius: 4px;

    .name {
      margin-left: 15px;
      font-size: 16px;
      color: #2b313d;
      font-weight: bold;
    }

    p {
      margin: 15px 0;
      font-size: 14px;
      color: #5e616b;
    }
  }

  .btn-group {
    border-bottom: 1px solid #e0e1e6;
    padding-bottom: 20px;

    button {
      height: 30px;
      line-height: 28px;
      width: 95px;
      border-color: #9d9ea7;

      &.red-btn {
        color: #e8302e;
        border-color: #e8302e;
      }

      &.gray-btn {
        color: #9d9ea7;
      }
    }
  }

  .notice {
    color:  #9D9EA7;
    font-size: 14px;
    margin: 15px;
    line-height: 1.4;
    text-align: justify;
  }
}

.normal {
  .paragraphs .content {
    font-size: 14px;
  }
}

.large {
  .paragraphs .content {
    font-size: 18px !important;
  }
}

.larger {
  .paragraphs .content {
    font-size: 22px !important;
  }
}
</style>
